package com.data.springbootdynamicdata.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.data.springbootdynamicdata.mapper.TestMapper;
import com.data.springbootdynamicdata.datasource.DataSourceContextHolder;
import com.data.springbootdynamicdata.datasource.DynamicDataSource;
import com.data.springbootdynamicdata.domain.DBInfo;
import com.data.springbootdynamicdata.domain.Test;
import com.data.springbootdynamicdata.mapper.DBInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/***
 *  Created with IntelliJ IDEA.
 *  Author:  wenlin
 *  Date:  2018/4/23 15:40
 *  Description:
 **/
@Component
public class LoadDataSource implements CommandLineRunner {
    @Autowired
    private DBInfoMapper dbInfoMapper;

    @Autowired
    TestMapper testMapper;

    @Override
    public void run(String... strings) throws Exception {
        //从数据库读取所有数据源数据
        List<DBInfo> dbInfos = dbInfoMapper.getDBInfo();
        Map<Object, Object> dataSourceMap = DynamicDataSource.getInstance().getDataSourceMap();
        for (DBInfo dbInfo : dbInfos) {
            System.out.println("dbName is -> " + dbInfo.getDbName() + "; dbIP is  -> " + dbInfo.getDbIp() + "; dbUser is  -> " + dbInfo.getDbUser() + "; dbPasswd is -> " + dbInfo.getDbPasswd());

            DruidDataSource dynamicDataSource = new DruidDataSource();
            dynamicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dynamicDataSource.setUrl("jdbc:mysql://" + dbInfo.getDbIp() + ":" + dbInfo.getDbPort() + "/" + dbInfo.getDbName() + "?characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull");
            dynamicDataSource.setUsername(dbInfo.getDbUser());
            dynamicDataSource.setPassword(dbInfo.getDbPasswd());
            dataSourceMap.put(dbInfo.getId(), dynamicDataSource);
        }
        DynamicDataSource.getInstance().setTargetDataSources(dataSourceMap);

        /**
         *  Description:动态切换数据源示例
         **/
        DataSourceContextHolder.setDBType("test1");
        List<Test> test1 = testMapper.getDes();
        System.out.println(test1.toString());
        DataSourceContextHolder.setDBType("test2");
        List<Test> test2 = testMapper.getDes();
        System.out.println(test2.toString());
        DataSourceContextHolder.setDBType("test3");
        List<Test> test3 = testMapper.getDes();
        System.out.println(test3.toString());
        DataSourceContextHolder.setDBType("default");
        List<DBInfo> list = dbInfoMapper.getDBInfo();
        System.out.println(list);
    }

}
